package com.wgke.kmmapp.net

import com.wgke.kmmapp.bean.Version
import io.ktor.client.*
import io.ktor.client.features.logging.*
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
//
class NetLoader(
    private val httpClient: HttpClient
) {
    suspend fun get(url: String): String {
        return httpClient.get<HttpResponse>(url).readText()
    }

    suspend fun <T> post(url: String, map: Any?, ks: KSerializer<T>): T? {
        Response.serializer(String.serializer())
        val json = httpClient.post<String>(url) {
            headers {
                append("X-App-Code", "zsjr")
                append("X-Trace-Log", "true")
                append("Content-Type", "application/json")
            }
            map?.let { body = it }
        }
        val value = convertJsonToObject(json, Response.serializer(ks))
        if (value.code == 200) {
            return value.data
        } else throw (NetError(value.code, value.msg))
    }

    /**解析*/
    private fun <T> convertJsonToObject(jsonString: String, serializer: DeserializationStrategy<T>): T {
        return Json {
            isLenient = true
            ignoreUnknownKeys = true
        }.decodeFromString(serializer, jsonString)
    }

}

@Serializable
data class Response<T>(val code: Int, val msg: String?, var data: T? = null)

data class NetError(var code: Int, var msg: String?) : Exception(msg ?: "")
